<script setup lang="ts">
import { cloneDeep } from 'lodash-es'
import { computed, nextTick, ref, toRefs } from 'vue'

const props = withDefaults(defineProps<{
    data?: any
    limit?: number
}>(), {
    limit: 100,
})

const emits = defineEmits(['onSuccess', 'doAdd'])
const visible = defineModel<boolean>()
const { data, limit } = toRefs(props)
const tableRef = ref()
const tableData = ref<any>([])

const getTableData = computed(() => {
    return tableData.value.length ? tableData.value.filter((v: any) => v.isDeleted === 0) : []
})

function doDel({ $index, row }) {
    if (!row?.id) {
        tableData.value.splice($index, 1)
    }
    else {
        tableData.value[$index].isDeleted = 1
    }
}

function doAdd() {
    const len = getTableData.value.length
    if (len >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    const target = getTableData.value[len - 1]
    // 校验上条数据 是否填写完整
    if (len && /^\s*$/.test(target.model)) {
        isNext = false
    }

    if (!isNext) {
        ElMessage.error(`请填写完整第${len}条规格型号`)
        return
    }

    const models = getTableData.value.map((v: any) => v.model)
    const arr = models.slice(0, models.length - 1)

    if (len > 1 && arr.includes(target.model)) {
        ElMessage.error(`第${len}条数据已存在`)
        return
    }

    tableData.value.push({
        categoryId: Number(data.value.categoryId),
        isDeleted: 0, // 0 未删除  1 已删除
        model: '',
    })

    if (tableData.value.length > 5) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 300)
        })
    }
}

function cancel() {
    visible.value = false
}

function doSave() {
    const target = getTableData.value

    // 重复校验
    const noRepeat = new Set([...getTableData.value.map((v: any) => v.model)])

    if (target.length !== noRepeat.size) {
        ElMessage.error(`存在重复规格型号`)
        return
    }

    const isEnpty = tableData.value.some((v: any) => !v.model || v.model.includes(' '))
    if (isEnpty) {
        ElMessage.error(`请填写完整再保存`)
        return
    }

    cancel()
    emits('onSuccess', cloneDeep(tableData.value))
}

function doBlur({ row }) {
    if (row.model === '') {
        ElMessage.error(`请输入变量名`)
        return
    }

    if (row.model.includes(' ')) {
        ElMessage.error(`请输入非空字符`)
    }
}

watch(visible, (val: any) => {
    if (val) {
        const target = data.value?.itemModels?.length ? data.value?.itemModels : []
        // 公式变量回显
        tableData.value = cloneDeep(target)
    }
}, {
    immediate: true,
})
</script>

<template>
    <el-dialog v-model="visible"
               title="配置规格型号"
               width="600"
               close-on-press-escape
               @cancel="cancel"
               @closed="cancel"
    >
        <el-table ref="tableRef"
                  :data="getTableData"
                  stripe
                  style="width: 100%"
                  height="300"
        >
            <el-table-column label="序号"
                             type="index"
                             width="55"
            />

            <el-table-column label="规格型号">
                <template #default="scope">
                    <el-input v-model="scope.row.model"
                              maxlength="100"
                              placeholder="请输入"
                              type="text"

                              clearable
                              show-word-limit
                              @blur="doBlur(scope)"
                    />
                </template>
            </el-table-column>

            <el-table-column label="操作"
                             width="100"
            >
                <template #default="scope">
                    <el-button link
                               @click="doDel(scope)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-button class="mt-20"
                   type="primary"
                   plain
                   @click="doAdd"
        >
            + 新增规格
        </el-button>

        <template #footer>
            <div class="text-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="doSave"
                >
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.dialog-content {
    .calculator-content {
        .input-box {
            height: 80px;
            border: 1px solid #e6e6e6;
            margin-top: 20px;
            border-radius: 5px;
            padding: 5px;
            overflow: hidden;
        }

        .calculator-show {
            width: 100%;
            display: flex;
            justify-content: space-between;
            gap: 20px;
            overflow: hidden;
            margin-top: 20px;

            .attributeShow {
                width: 65%;
                display: grid;
                grid-template-columns: repeat(4, 1fr);
                grid-template-rows: repeat(auto-fill, 40px);
                gap: 10px;

                .item-block {
                    width: 100%;
                    border: 1px solid #e6e6e6;
                    border-radius: 5px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>
